package xyz.zzzxb.snake.game;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import xyz.zzzxb.snake.SnakeMain;
import xyz.zzzxb.snake.ui.Food;
import xyz.zzzxb.snake.ui.Snake;
import xyz.zzzxb.snake.ui.Wall;

/**
 * @author Zzzxb  2019/10/12 20:16
 * @description:
 */
public class GameWorld {
    private GameController gameController;
    private SpriteBatch batch;
    private Wall wall;
    private Snake snake;
    private Food food;

    private GameWorld() {
    }

    public GameWorld(GameController gameController) {
        batch = new SpriteBatch();
        this.gameController = gameController;
        wall = new Wall();
        snake = new Snake();
        food = new Food();
        new GameSound();
    }

    public void init() {
        soundManager();
        wall.init();
        snake.init();
        food.init();
    }

    public void soundManager() {
        GameSound.getEatFoodSound().stop();
        GameSound.getGameOverMusic().stop();
        GameSound.getBackgroundMusic().stop();
        GameSound.getBackgroundMusic().setLooping(true);
        GameSound.getBackgroundMusic().play();
    }

    public void render() {
            batch.begin();

            wall.draw(batch);
            food.draw(batch);
            snake.draw(batch);

            batch.end();
    }


    public void update(float deltaTime) {
        snake.controller(deltaTime);
        eatFood();

        if (Gdx.input.isKeyPressed(Input.Keys.Q)) {
            System.exit(0);
            return;
        }
        if (Gdx.input.isKeyPressed(Input.Keys.R)) {
            init();
            return;
        }
    }

    private void eatFood() {
        int[] snakeXy = snake.getXy();
        int[] foodXY = food.getXyFood();
        if (snakeXy[0] == foodXY[0] && snakeXy[1] == foodXY[1]) {
            GameSound.getEatFoodSound().play();
            snake.awardedMarks();
            food.createFood();
        }
    }

    public void dispose() {
        wall.dispose();
        snake.dispose();
        food.dispose();
    }
}
